# -*- coding: utf-8 -*-
import copy
import tkinter.messagebox
from pypinyin import lazy_pinyin, Style
import pyautogui
import os
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import pandas as pd
import random
import threading
import webbrowser
import pyperclip
import time
from pynput import keyboard
from pynput.keyboard import Listener
import threading

# 全局状态
class AppState:
    def __init__(self):
        self.ai_web=[
    ("豆包", "https://www.doubao.com/chat/17475452365708290"),
    ("通义千问", "https://www.tongyi.com/"),
    ("deepseek", "https://chat.deepseek.com/"),
    ("元宝", "https://yuanbao.tencent.com/chat/naQivTmsDa/afd21b6e-d91d-4e58-a285-bf19f41bdaf9"),
    ("kimi", "https://kimi.moonshot.cn/chat/%7Ccp6n231mqu05p0eb5mdg?index=0&tu=1"),
    ("文心一言", "https://yiyan.baidu.com/"),
    ("百川AI", "https://ying.baichuan-ai.com/chat"),
]
        self.file_path=[
            ("生活文档",r"C:\Users\liuzc\Desktop\python试验\生活\生活（测试）.xlsx"),
            ("实习相关",r"C:\Users\liuzc\Desktop\实习简历"),
            ("应试相关",r"C:\Users\liuzc\Desktop\应试相关"),
            ("前端专用",r"C:\Users\liuzc\Desktop\前端专用"),
            ("前端文档",r"C:\Users\liuzc\Desktop\python试验\程序语言\JavaScript.xlsx"),
            ("python文档",r"C:\Users\liuzc\Desktop\python试验\程序语言\python刷题试验.xlsx"),
                        ]
        self.web_path=[
            ("百度","https://www.baidu.com/"),
            ("B站","https://www.bilibili.com/"),
                       ]

        self.open_dic={}                       #这个就是输入enter键快速跳转用的
        for l in self.ai_web+self.web_path+self.file_path:
            pinyin=lazy_pinyin(l[0], style=Style.NORMAL, errors='ignore')
            pinyin=''.join(pinyin)
            self.open_dic[l[0]+"-"+pinyin]=l[1]
            self.open_dic[l[0]]=l[1]
        print(self.open_dic)
        self.current_list=None

        self.ai_website_index=0
        self.focus_point=0        #焦点 0->文本框 1->常用ai框 2->常用文件/文件夹框 3->常用网页框 4->下面的推荐框

        self.popup_menu_window=None
        self.website_listbox=None

state = AppState()

# 主窗口
root = tk.Tk()
root.title("聚焦(alt+space唤醒）")
root.geometry("1300x500+380+300")

# ---------------------- 功能函数 ----------------------

# ---------------------- UI 组件 ----------------------
# 左侧文本框
left_text = scrolledtext.ScrolledText(root, width=42, height=7, font=("微软雅黑", 14))
left_text.grid(row=0, column=1, padx=(10, 5), pady=10, rowspan=2, sticky='n')

# 右侧按钮（显示“常用常用AI”)
ai_btn = tk.Button(root, text="常用AI ▼", width=15, height=2, font=("微软雅黑", 12))
ai_btn.grid(row=0, column=2, padx=(5, 10), pady=10, sticky='n')

file_btn=tk.Button(root, text="常用文件 ▼", width=15, height=2, font=("微软雅黑", 12))
file_btn.grid(row=0, column=3, padx=(5, 10), pady=10, sticky='n')

web_btn=tk.Button(root, text="常用网页 ▼", width=15, height=2, font=("微软雅黑", 12))
web_btn.grid(row=0, column=4, padx=(5, 10), pady=10, sticky='n')

label_show = tk.Label(root, text="1", font=("微软雅黑", 14))    #显示在上面的文字
label_show .grid(row=5, column=1, sticky='nw', padx=10)
# ---------------------- 下拉菜单（隐藏，鼠标/键盘触发时弹出）----------------------
# 全局变量：用于保存弹出的菜单窗口和 listbox

def open_website_by_index(index):
    """根据索引打开网址"""
    if 0 <= index < len(state.current_list):
        url = state.current_list[index][1]
        #判断是否网址，是的话打开网址，否则打开本地本地文件
        lower_url = url.lower().strip()
        # 判断是否以常见 URL 协议开头
        if lower_url.startswith(('http://', 'https://', 'ftp://', 'www.')):
            # 如果是以 www. 开头，补全为 http://
            if lower_url.startswith('www.'):
                url = 'http://' + url  # 保持原始大小写拼接
            webbrowser.open(url)
        else:
            # 否则视为本地文件或路径
            os.startfile(url)
        hide_popup_menu()
        # 清空左侧
        left_text.delete(1.0, tk.END)
        root.withdraw()  # 最小化主窗口



def hide_popup_menu():
    """关闭弹出菜单"""
    if state.popup_menu_window:
        state.popup_menu_window.destroy()
        state.popup_menu_window = None

def show_website_menu(event=None):
    """显示自定义的可键盘操作的弹出菜单"""

    # 避免重复创建
    hide_popup_menu()

    # 创建无边框浮动窗口
    state.popup_menu_window = tk.Toplevel(root)
    state.popup_menu_window.overrideredirect(True)  # 去除窗口边框
    if state.focus_point==0:
        state.popup_menu_window.geometry("+%d+%d" % (
            left_text.winfo_rootx(),
            left_text.winfo_rooty() + left_text.winfo_height()
        ))

        width = 40
    if state.focus_point==1:
        state.popup_menu_window.geometry("+%d+%d" % (
            ai_btn.winfo_rootx(),
            ai_btn.winfo_rooty() + ai_btn.winfo_height()
        ))
        state.current_list=state.ai_web
        width = 20
    elif state.focus_point==2:
        state.popup_menu_window.geometry("+%d+%d" % (
            file_btn.winfo_rootx(),
            file_btn.winfo_rooty() + file_btn.winfo_height()
        ))
        state.current_list=state.file_path
        width = 20
    elif state.focus_point==3:
        state.popup_menu_window.geometry("+%d+%d" % (
            web_btn.winfo_rootx(),
            web_btn.winfo_rooty() + web_btn.winfo_height()
        ))
        state.current_list = state.web_path
        width=20
    state.popup_menu_window.config(bg="#f0f0f0", highlightthickness=1, highlightbackground="gray")

    # 创建 Listbox
    state.website_listbox = tk.Listbox(
        state.popup_menu_window,
        font=("微软雅黑", 12),
        height=len(state.current_list),
        width=40,
        activestyle='none'
    )
    state.website_listbox.pack(padx=1, pady=1)

    # 插入菜单项
    for name, _ in state.current_list:
        state.website_listbox.insert(tk.END, name)

    # 默认选中第一个
    state.website_listbox.select_set(0)
    state.website_listbox.activate(0)
    state.website_listbox.focus_set()

    # 绑定事件
    def on_listbox_keypress(event):
        max_idx = len(state.current_list) - 1
        cur_sel = state.website_listbox.curselection()
        current = cur_sel[0] if cur_sel else 0
        # print('state.focus_point',state.focus_point)
        if event.keysym == 'Up':
            # next_ = max(0, current - 1)
            next_ = current - 1
            if current - 1 < 0:
                next_ = max_idx
            state.website_listbox.selection_clear(current)
            state.website_listbox.select_set(next_)
            state.website_listbox.activate(next_)
            return "break"

        elif event.keysym == 'Down':
            # next_ = min(max_idx, current + 1)
            next_=current+1
            if current+1>max_idx:
                next_=0
            state.website_listbox.selection_clear(current)
            state.website_listbox.select_set(next_)
            state.website_listbox.activate(next_)
            return "break"

        elif event.keysym == 'Return':
            idx = state.website_listbox.curselection()[0]
            open_website_by_index(idx)
            return "break"

        elif event.keysym == 'Left':
            state.focus_point -= 1
            if state.focus_point==0:
                left_text.focus_set()
                return "break"
            hide_popup_menu()

            show_website_menu()
            # return "break"

        elif event.keysym == 'Right':
            hide_popup_menu()
            if state.focus_point==3:        #这里对应左右按钮的数量
                show_website_menu()
            else:
                state.focus_point+=1
                show_website_menu()
            return "break"

        elif event.keysym == 'Escape':
            hide_popup_menu()
            left_text.focus_set()
            state.focus_point=0
            return "break"

    def handle_click_selection():
        """处理鼠标点击选择后的打开操作"""
        try:
            selection = state.website_listbox.curselection()
            if selection:
                index = selection[0]
                open_website_by_index(index)
        except Exception as e:
            print("点击处理出错:", e)

    # 在 show_website_menu 中，创建 Listbox 并绑定键盘后，添加：
    state.website_listbox.bind('<Double-Button-1>', lambda e: root.after(50, lambda: handle_click_selection()))

    state.website_listbox.bind('<KeyPress>', on_listbox_keypress)       #键盘事件
    state.popup_menu_window.bind('<FocusOut>', lambda e: root.after(10, hide_popup_menu))

#-----------------------------------按钮事件绑定-----------------
def btn_click(statet):
    state.focus_point=statet
    print(state.focus_point)
    show_website_menu()
# 让鼠标点击也能弹出新菜单

ai_btn.config(command=lambda: btn_click(1))
file_btn.config(command=lambda: btn_click(2))
web_btn.config(command=lambda: btn_click(3))



# ---------------------- 键盘事件绑定 ----------------------
def on_space_press(event):
    if event.keysym == 'space':
        # label_show.config(text=time.time())
        # return "break"
        pass
    elif event.keysym == 'Up':
        pass
    elif event.keysym == 'Down':
        pass
    elif event.keysym == 'Left':
        state.focus_point=0

    elif event.keysym == 'Right':
        # 当在 left_text 且按下右方向键，跳转到 website_btn
        if state.focus_point == 0:
            state.focus_point=1
            ai_btn.focus_set()
            state.current_list = state.ai_web
            show_website_menu()  # 自动弹出菜单（可选）
        else:
            state.focus_point=0
        return "break"

    elif event.keysym == 'Return':
        state.current_list=[]
        current_input=left_text.get(1.0, tk.END).strip()
        for key in state.open_dic:
            if current_input in key:
                state.current_list.append((key,state.open_dic[key]))
        if not state.current_list:
            state.current_list=[(f"在互联网搜索搜索{current_input}","https://www.baidu.com/")]
            pyperclip.copy(current_input)
        # tkinter.messagebox.showinfo(left_text.get(1.0, tk.END).strip())
        show_website_menu()
        return "break"
    elif event.keysym == 'Escape':
        # tkinter.messagebox.showinfo("","")
        root.withdraw()
    return "break"

# 绑定键盘事件
root.bind('<KeyPress>', on_space_press)

# 确保 left_text 可以获取焦点
left_text.focus_set()

# ---------------------- 全局键盘监听唤醒窗口 ----------------------
def bring_to_front():
    """唤醒窗口，并确保 root 获得焦点和按键事件可用"""
    root.deiconify()  # 恢复窗口
    root.attributes('-topmost', True)
    root.attributes('-topmost', False)
    state.focus_point=0


# 全局变量用于跟踪修饰键状态
alt_pressed = False

def on_press(key):
    global alt_pressed

    #---------------------------用于alt+space唤醒--------------------------
    # 检测Alt 是否被按下
    if key == keyboard.Key.alt_l or key == keyboard.Key.alt_r:
        alt_pressed = True

    # 检测Alt + Space
    elif key == keyboard.Key.space:
        if alt_pressed:
            root.after(0, bring_to_front)
            # 可选：模拟点击屏幕中心
            threading.Thread(target=move_and_click_center, daemon=True).start()

    else:
        return

def on_release(key):
    global  alt_pressed
    # 释放时重置状态
    if key == keyboard.Key.alt_l or key == keyboard.Key.alt_r:
        alt_pressed = False

def move_and_click_center():
    """移动鼠标到屏幕中心并点击"""
    screen_width, screen_height = pyautogui.size()
    center_x = screen_width // 3
    center_y = screen_height // 2
    pyautogui.moveTo(center_x, center_y, duration=0.1)
    pyautogui.click()
    print(f"鼠标已移动到屏幕中心 ({center_x}, {center_y}) 并点击")

def start_global_listener():
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

# 启动监听线程
listener_thread = threading.Thread(target=start_global_listener, daemon=True)
listener_thread.start()
#---------------------------------------------------

root.mainloop()